//
//  HBSettingController.m
//  HeartBeat
//
//  Created by karong on 2023/9/7.
//

#import "HBSettingController.h"
#import "AppDelegate.h"
#import "HBSettingFooterView.h"
#import <SDWebImage/SDWebImage.h>

@interface HBSettingController ()<WSSettingFootViewDelegate>

@property (weak, nonatomic) IBOutlet UICollectionView *listView;
@property (nonatomic, strong) NSArray * dataArray;

@end

@implementation HBSettingController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)delUserRequest {
    [HBRequest delUserWithSuccess:^{
        [HBToast simple:WSLocalized(@"註銷成功")];
        [self.navigationController popToRootViewControllerAnimated:YES];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

///個人信息
- (void)userInfoAction {
    if (appUserCenter.isLogin) {
        [ViewManager pushUserInfoVCWithUser:appUserCenter inController:self];
    }
    else {
        [((AppDelegate*)([UIApplication sharedApplication].delegate)) initMainPage];
    }
    
}

///自動購買
- (void)autoPayAction {
    appConfig.isAutoPay = !appConfig.isAutoPay;
    self.dataArray = nil;
    [self.listView reloadData];
}

///清除緩存
- (void)clearCacheAction {
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:nil];
    [HBToast simple:WSLocalized(@"操作成功")];
    self.dataArray = nil;
    [self.listView reloadData];
}

///用戶協議
- (void)userAgreementAction {
    [ViewManager pushWebVCWithUrl:API_HEARTBEAT_AGREEMENT_USER titleStr:WSLocalized(@"用戶協議") inController:self];
}

///隱私政策
- (void)privacyAction {
    [ViewManager pushWebVCWithUrl:API_HEARTBEAT_AGREEMENT_PRIVACY titleStr:WSLocalized(@"隱私政策") inController:self];
}

///檢查更新
- (void)checkUpdataAction {
    if (appConfig.startConfig.ios_prompt_update_version > [[HBTool getVersionCode] integerValue]) {
        [ViewManager showNewVersionCodeAlterInController:self];
    }
    else {
        [HBToast simple:WSLocalized(@"當前已是最新版本")];
    }
}

///賬號註銷
- (void)delUserAction {
    [ViewManager showDeleteUserAlterWithConfirmHandle:^{
        [self delUserRequest];
    } inController:self];
}

///退出登錄
- (IBAction)logOutAction {
    [appUserCenter logOut];
    [HBToast simple:WSLocalized(@"退出成功")];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
#pragma mark UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"kcell" forIndexPath:indexPath];
    NSDictionary * dic = self.dataArray[indexPath.row];
    UILabel * label = [cell viewWithTag:101];
    label.text = dic[@"title"];
    UILabel * subLabel = [cell viewWithTag:102];
    subLabel.text = dic[@"subTitle"];
    UIButton * updataBtn = [cell viewWithTag:103];
    if ([WSLocalized(@"檢查更新")isEqualToString:dic[@"title"]] && appConfig.startConfig.ios_prompt_update_version > [[HBTool getVersionCode] integerValue]) {
        updataBtn.hidden = NO;
    }
    else {
        updataBtn.hidden = YES;
    }
    UIImageView * image = [cell viewWithTag:104];
    image.image = IMG(dic[@"image"]);
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize size = CGSizeZero;
    size.width = HBScreenWidth;
    size.height = 54;
    return size;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary * dic = self.dataArray[indexPath.row];
    SEL sel = NSSelectorFromString(dic[@"sel"]);
    if ([self respondsToSelector:sel]) {
        [self performSelector:sel withObject:nil];
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        HBSettingFooterView * settingFooterView;
        if (!settingFooterView) {
            settingFooterView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"HBSettingFooterView" forIndexPath:indexPath];
            settingFooterView.delegate = self;
        }
        return settingFooterView;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    CGSize size = CGSizeZero;
    if (appUserCenter.isLogin) {
        size.width = HBScreenWidth;
        size.height = 44 + 82;
    }
    return size;
}

#pragma mark WSSettingFootViewDelegate
- (void)settingFootViewLogOutAction {
    [self logOutAction];
}

- (void)settingFootViewDelUserAction {
    [self delUserAction];
}

- (NSArray *)dataArray {
    if (!_dataArray) {
        _dataArray = @[@{@"title":WSLocalized(@"個人信息"),
                         @"subTitle":@"",
                         @"image":@"icon_more",
                         @"sel":@"userInfoAction"},
                       @{@"title":WSLocalized(@"自動購買章節"),
                         @"subTitle":@"",
                         @"image":(appConfig.isAutoPay)?@"ic_setup_open":@"ic_setup_close",
                         @"sel":@"autoPayAction"},
                       @{@"title":WSLocalized(@"清除緩存"),
                         @"subTitle":KEmptyStr([self cacheSize]),
                         @"image":@"icon_more",
                         @"sel":@"clearCacheAction"},
                       @{@"title":WSLocalized(@"用戶協議"),
                         @"subTitle":@"",
                         @"image":@"icon_more",
                         @"sel":@"userAgreementAction"},
                       @{@"title":WSLocalized(@"隱私政策"),
                         @"subTitle":@"",
                         @"image":@"icon_more",
                         @"sel":@"privacyAction"},
                       @{@"title":WSLocalized(@"檢查更新"),
                         @"subTitle":[NSString stringWithFormat:@"v%@", [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"]],
                         @"image":@"icon_more",
                         @"sel":@"checkUpdataAction"}];
    }
    return _dataArray;
}

- (NSString *)cacheSize {
    NSUInteger size = [[SDImageCache sharedImageCache] totalDiskSize];
    NSString *cacheStr = [self fileSizeWithInterge:size];
    return cacheStr;
}

- (NSString *)fileSizeWithInterge:(NSInteger)size {
      // 1k = 1024, 1m = 1024k
      if (size < 1024) { //小於1k
          return [NSString stringWithFormat:@"%ldB",(long)size];
      } else if (size < 1024 * 1024) { //小於1M
          CGFloat cFloat = size / 1024;
          return [NSString stringWithFormat:@"%.1fK",cFloat];
      } else if (size < 1024 * 1024 * 1024) { //小於1G
          CGFloat cFloat = size / (1024 * 1024);
          return [NSString stringWithFormat:@"%.1fM",cFloat];
      } else { //大於1G
          CGFloat cFloat = size / (1024 * 1024 * 1024);
          return [NSString stringWithFormat:@"%.1fG",cFloat];
      }
}
@end
